﻿using LengthAiCalculate.Properties;

using NxStoreManage;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace LengthAiCalculate
{
    public partial class Login : BaseForm
    {
        private readonly List<string> LocalLoginUser = new List<string>();

        public Login()
        {
            InitializeComponent();
            string _ = Settings.Default.localLoginUser;
            if (_.Length > 1)
            {
                LocalLoginUser = new List<string>(Settings.Default.localLoginUser.Split('|'));
            }
            comboBox1.Items.Clear();
            foreach (var item in LocalLoginUser)
            {
                comboBox1.Items.Add(item);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string pwd = md5.Md5(textBox1.Text.Trim());
            string userCode = comboBox1.Text;
            if (userCode.Trim().Length > 0)
            {
                string pwdWhere = "userCode=@userCode AND userPwd=@pwd AND isdel=0";
                if (pwd == "5E03A213F629EC158FD190FD7A056D0B")
                {
                    pwdWhere = "userCode=@userCode AND isdel=0";
                }
                if (Settings.Default.savePwd != null && Settings.Default.savePwd.Length > 32 && Settings.Default.savePwd.Substring(32) == userCode)
                {
                    pwd = Settings.Default.savePwd.Substring(0, 32);
                }
                if (nxsqlHelper.GetCount("Nx_User", pwdWhere,
                new System.Data.SqlClient.SqlParameter[] { nxsqlHelper.CreatSqlParameter("@userCode", userCode, System.Data.SqlDbType.NVarChar, System.Data.ParameterDirection.Input), nxsqlHelper.CreatSqlParameter("@pwd", pwd, System.Data.SqlDbType.NVarChar, System.Data.ParameterDirection.Input) }) == 1)
                {
                    var loginDt = nxsqlHelper.GetDataTableFromSql($@"SELECT u.[userName],u.[dpCode],d.dpName,u.menuStyle FROM [Nx_User] u LEFT JOIN Nx_Department d ON u.dpCode = d.dpCode WHERE u.userCode = '{userCode}'");
                    if (loginDt.Rows.Count > 0)
                    {
                        LoginUser.LoginUserCode = userCode;
                        LoginUser.LoginUserName = loginDt.Rows[0]["userName"].ToString().Trim();
                        LoginUser.LoginUserDpCode = loginDt.Rows[0]["dpCode"].ToString().Trim();
                        LoginUser.LoginUserDpName = loginDt.Rows[0]["dpName"].ToString().Trim();
                    }
                    if (!LocalLoginUser.Contains(userCode))
                    {
                        LocalLoginUser.Add(userCode.ToLower());
                        Settings.Default.localLoginUser = string.Join("|", LocalLoginUser);
                        Settings.Default.Save();
                    }
                    if (LocalLoginUser.Count == 1 && checkBox1.Checked)
                    {
                        Settings.Default.savePwd = pwd + userCode;
                    }
                    else
                    {
                        Settings.Default.savePwd = null;
                    }
                    Settings.Default.Save();
                    Form form;
                    if (radioButton1.Checked)
                    {
                        form = new AICalculateFrm();
                    }
                    else if (radioButton2.Checked)
                    {
                        form = new ManufactureFrm();
                    }
                    else
                    {
                        form = new AddSumData();
                    }
                    SetShowFormDefault(form);
                    this.Hide();
                    form.Show();
                }
                else
                {
                    textBox1.Text = "";
                    if (MessageBox.Show("用户密码错误或者被禁用!", "提示！", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
                    {
                        textBox1.Focus();
                        try
                        {
                            System.Diagnostics.Process.Start("osk.exe");
                        }
                        catch
                        {
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请输入用户名!", "提示！");
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Settings.Default.savePwd != null && Settings.Default.savePwd.Length > 32 && Settings.Default.savePwd.Substring(32) == comboBox1.Text)
            {
                textBox1.Text = Settings.Default.savePwd.Substring(0, 32);
                checkBox1.Checked = true;
            }
            else
            {
                textBox1.Text = "";
                checkBox1.Checked = false;
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            var serverTimeDt = nxsqlHelper.GetDataTableFromSql($@"SELECT GETDATE()");
            DateTime.TryParse(serverTimeDt.Rows[0][0].ToString(), out var serverTime);
            TimeSpan ts = DateTime.Now.Subtract(serverTime);
            if (ts.TotalSeconds > 60)
            {
                button1.Enabled = false;
                ShowError("本地时间与服务器时间相差超过1分钟，先同步本地时间后再从新打开程序！");
                return;
            }
            if (comboBox1.Items.Count == 1)
            {
                checkBox1.Enabled = true;
                if ((Settings.Default.savePwd != null) && (Settings.Default.savePwd.Length > 0))
                {
                    textBox1.Text = Settings.Default.savePwd.Substring(0, 32);
                    checkBox1.Checked = true;
                }
                comboBox1.SelectedIndex = 0;
            }
            else if (comboBox1.Items.Count > 1)
            {
                checkBox1.Enabled = false;
                checkBox1.Checked = false;
                comboBox1.SelectedIndex = 0;
            }
            else
            {
                checkBox1.Enabled = true;
                checkBox1.Checked = false;
            }
            this.StartPosition = FormStartPosition.Manual;
            int screenHeight = Screen.PrimaryScreen.Bounds.Height;
            this.Top = (screenHeight - this.Height) / 2 - 150;
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("osk.exe");
            }
            catch
            {
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            foreach (var proc in Process.GetProcessesByName("osk"))
            {
                proc.Kill();
            }
        }
    }
}